home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: mxsld2.pd.infn.it!LORETI
- From: loreti@mxsld2.pd.infn.it (Maurizio Loreti)
- Subject: Re: gets() question
- X-Nntp-Posting-Host: mxsld2.pd.infn.it
- Message-ID: <DKupzL.7Ap@news.cern.ch>
- Sender: news@news.cern.ch (USENET News System)
- Reply-To: loreti@mxsld2.pd.infn.it
- Organization: I.N.F.N. Padova - CDF/CMS VAXcluster
- References: <4cosgf$rir@newsbf02.news.aol.com>
- Date: Mon, 8 Jan 1996 07:25:48 GMT
-
- In article <4cosgf$rir@newsbf02.news.aol.com>, simpsondg@aol.com (SimpsonDG) writes:
- >Can any of you C gurus out there help me with this? I have a problem with
- >gets() that I don't understand. The program below will successfully input
- >the string s[0], but will simply ignore the gets() that inputs s[1] and
- >goes on to ask for i[1]. What's the deal? A little experimenting seems
- >to indicate that the problem arises when I have a gets() following a
- >scanf() -- e.g., a program using only gets() or only scanf() works fine.
- >
- >David Simpson
- >
- >--------------------------------------------------------------------------
- >-------------------
- >
- >#include "stdio.h"
- >
- >void main(void)
- >{
- > int i[5];
- > char s[3][10];
- >
- > printf ("Enter s[0]: ");
- > gets (s[0]);
- >
- > printf ("Enter i[0]]: ");
- > scanf ("%d",&i[0]);
- >
- > printf ("Enter s[1]: ");
- > gets (s[1]); /* this gets() doesn't wait for input */
- >
- > printf ("Enter i[1]]: ");
- > scanf ("%d",&i[1]);
- >}
-
- This is covered in the comp.lang.c FAQ list, that you are supposed to
- check before posting, and that is available from RTFM.mit.edu in
- pub/usenet/comp.lang.c/*.
-
- 12.18: I'm reading a number with scanf %d and then a string with
- gets(), but the compiler seems to be skipping the call to
- gets()!
-
- A: scanf %d won't consume a trailing newline. If the input number
- is immediately followed by a newline, that newline will
- immediately satisfy the gets().
-
- As a general rule, you shouldn't try to interlace calls to
- scanf() with calls to gets() (or any other input routines);
- scanf's peculiar treatment of newlines almost always leads to
- trouble. Either use scanf() to read everything or nothing.
-
- See also questions 12.20 and 12.23.
-
- References: ANSI Sec. 4.9.6.2; ISO Sec. 7.9.6.2; H&S Sec. 15.8
- pp. 357-64.
- --
- Maurizio Loreti http://mvxpd5.pd.infn.it/wwwcdf/mlo.html
- Un. of Padova, Dept. of Physics - Padova, Italy loreti@padova.infn.it
-